package com.hcc.security.service.serviceImpl;

import io.jsonwebtoken.lang.Collections;
import java.util.Collection;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

/**
 * @version 1.0
 * @author: Administrator
 * @date: 2019/4/28
 */
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {

  /**
   * 决策方法：权限判断
   *
   * @param authentication 用户的身份信息;
   *
   * @param object 包含客户端发起的请求的request信息
   * 可转换为 HttpServletRequest request = ((FilterInvocation)
   * @param configAttributes 是MyInvocationSecurityMetadataSource的
   * getAttributes(Object object)这个方法返回的结果，此方法是为了判定用户请求的
   * url 是否在权限表中，如果在权限表中，则返回给 decide 方法
   * 用来判定用户是否有此权限;如果不在权限表中
   */
  @Override
  public void decide(Authentication authentication, Object object,
      Collection<ConfigAttribute> configAttributes)
      throws AccessDeniedException, InsufficientAuthenticationException {
   if(Collections.isEmpty(configAttributes)){
     return;
   }
   for(GrantedAuthority ga : authentication.getAuthorities()){
     if(configAttributes.contains(ga.getAuthority())){
       return;
     }
   }
   //TODO 自定义返回权限异常信息
   throw  new AccessDeniedException("没有访问权限");
  }

  @Override
  public boolean supports(ConfigAttribute attribute) {
    return true;
  }

  @Override
  public boolean supports(Class<?> clazz) {
    return true;
  }
}
